import os
from pydub import AudioSegment

def trim_mp3(input_file, start_sec, end_sec, output_file):
    """
    Trim MP3 file from start_sec to end_sec and save to output_file
    
    Args:
        input_file (str): Input MP3 file path
        start_sec (int): Start time in seconds
        end_sec (int): End time in seconds 
        output_file (str): Output MP3 file path
    """
    try:
        # Load MP3 file
        audio = AudioSegment.from_mp3(input_file)
        
        # Convert seconds to milliseconds
        start_ms = start_sec * 1000
        end_ms = end_sec * 1000
        
        # Extract the specified portion
        extracted_audio = audio[start_ms:end_ms]
        
        # Export the trimmed audio
        extracted_audio.export(output_file, format="mp3")
        print(f"Successfully trimmed {input_file} to {output_file}")
        
    except Exception as e:
        print(f"Error processing {input_file}: {str(e)}")

def main():
    # Directory containing MP3 files
    input_dir = "beijing"
    
    # Create output directory if it doesn't exist
    output_dir = "beijing_trimmed"
    os.makedirs(output_dir, exist_ok=True)
    
    # Example: trim from 5 seconds to 10 seconds
    start_time = 0  # Change this to your desired start time
    end_time = 2.5   # Change this to your desired end time
    
    # Process all MP3 files in the directory
    for filename in os.listdir(input_dir):
        if filename.endswith(".mp3"):
            input_path = os.path.join(input_dir, filename)
            output_path = os.path.join(output_dir, f"trimmed_{filename}")
            trim_mp3(input_path, start_time, end_time, output_path)

if __name__ == "__main__":
    main() 